from django.contrib import admin, messages
from django.contrib.admin.filters import SimpleListFilter
from django.utils.translation import gettext_lazy as _
from django.utils.html import format_html

from utils.model import NoDeleteSelectModelAdmin
from apps.app_ai.forms import AIHubServiceForm
from apps.app_ai.models import AIHubService
from apps.app_ai.managers.aihub import AIHubServiceManager


class AIHubServiceOrgFilter(SimpleListFilter):
    title = _("机构")
    parameter_name = 'org_id'

    def lookups(self, request, model_admin):
        r = AIHubService.objects.select_related('org_data_center__organization').order_by('sort_weight').values_list(
            'org_data_center__organization_id', 'org_data_center__organization__name'
        )
        d = {i[0]: i[1] for i in r}
        return [(k, v) for k, v in d.items()]

    def queryset(self, request, queryset):
        org_id = request.GET.get(self.parameter_name)
        if org_id:
            return queryset.filter(org_data_center__organization_id=org_id)


@admin.register(AIHubService)
class AIHubServiceAdmin(NoDeleteSelectModelAdmin):
    form = AIHubServiceForm
    list_display_links = ('id',)
    list_display = ('id', 'name', 'name_en', 'org_data_center', 'organization_name', 'sort_weight',
                    'status', 'endpoint_url', 'username', 'password', 'raw_password',
                    'creation', 'modification', 'version', 'version_update_time', 'longitude', 'latitude', 'remarks')
    search_fields = ['name', 'name_en', 'endpoint_url', 'remarks']
    list_filter = [AIHubServiceOrgFilter, 'status']
    list_select_related = ('org_data_center', 'org_data_center__organization')
    raw_id_fields = ('org_data_center',)
    list_editable = ('sort_weight',)

    readonly_fields = ('password',)
    fieldsets = (
        (_('说明、备注'), {'fields': ('remarks', 'sort_weight')}),
        (_('服务配置信息'), {
            'fields': ('org_data_center', 'name', 'name_en',
                       'version', 'version_update_time', 'status', 'endpoint_url',
                       'username', 'password', 'change_password')
        }),
        (_('其他配置信息'), {'fields': ('longitude', 'latitude')}),
        (_('联系人信息'), {
            'fields': ('contact_person', 'contact_email', 'contact_telephone', 'contact_fixed_phone', 'contact_address')
        })
    )

    actions = ['update_service_version']

    @admin.action(description=_("更新服务版本信息"))
    def update_service_version(self, request, queryset):
        count = 0
        for service in queryset:
            if service.status != AIHubService.Status.ENABLE.value:
                continue

            ok = AIHubServiceManager.update_service_version(service=service)
            if ok is True:
                count += 1

        if count > 0:
            self.message_user(request, _("更新版本数量:") + str(count), level=messages.SUCCESS)
        else:
            self.message_user(request, _("没有更新任何服务单元版本"), level=messages.SUCCESS)

    @admin.display(description=_("机构"))
    def organization_name(self, obj):
        if not obj.org_data_center or not obj.org_data_center.organization:
            return ''

        return obj.org_data_center.organization.name

    @admin.display(description=_("原始密码"))
    def raw_password(self, obj):
        passwd = obj.raw_password()
        if not passwd:
            return passwd

        return format_html(f'<div title="{passwd}">******</div>')

    def has_delete_permission(self, request, obj=None):
        return False
